# 检查本地是否有MySQL镜像
local_mysql_images=$(docker images -q mysql)
if [ -n "$local_mysql_images" ]; then
    echo "本地已存在MySQL镜像。"
else
    # 从阿里云镜像仓库拉取MySQL
    echo "开始从仓库拉取MySQL..."
    docker pull mysql
    if [ $? -eq 0 ]; then
        echo "MySQL镜像拉取成功。"
    else
        echo "MySQL镜像拉取失败，请检查网络或镜像名称是否正确。"
    fi
fi

# 启动MySQL容器
docker run --name mysql_node_1 -d -p 6606:3306 -e MYSQL_ROOT_PASSWORD=root -v ./mysql/data1:/var/lib/mysql mysql
docker run --name mysql_node_2 -d -p 6607:3306 -e MYSQL_ROOT_PASSWORD=root -v ./mysql/data2:/var/lib/mysql mysql
docker run --name mysql_node_3 -d -p 6608:3306 -e MYSQL_ROOT_PASSWORD=root -v ./mysql/data3:/var/lib/mysql mysql
docker run --name mysql_node_4 -d -p 6609:3306 -e MYSQL_ROOT_PASSWORD=root -v ./mysql/data4:/var/lib/mysql mysql

# 生成密钥
cd chainmaker-go/scripts
./prepare_pk.sh 4 1

# 编译
./build_release.sh

# 解压
cd ../../
if [ -d "release" ]; then
    rm -rf "release"
fi
mkdir -p "release"
echo "===> Unzip chainmaker installation package"
RELEASE_PATH=./chainmaker-go/build/release
for file in `ls $RELEASE_PATH`
do
    if [[ $file == chainmaker* ]] && [[ $file == *gz ]]; then
        echo "decompression $RELEASE_PATH/$file"
        tar -zxf $RELEASE_PATH/$file -C ./release
    fi
done

# 修改配置
i=0
port=6605
for file in `ls ./release`
do
    if [ $file ]; then
        ((i++))
        ((port++))
        echo "ChangeConfig ==> ./release/"$file
        # 开启SQL支持
        cp ./release/$file/config/node$i/chainconfig/bc1.yml ./release/$file/config/node$i/chainconfig/bc1.yml.backup
        sed -i 's/enable_sql_support: false/enable_sql_support: true/g' ./release/$file/config/node$i/chainconfig/bc1.yml
        # sed -i 's/hash: SHA256/hash: SM3/g' ./release/$file/config/node$i/chainconfig/bc1.yml
        
        # 配置数据库
        cp ./release/$file/config/node$i/chainmaker.yml ./release/$file/config/node$i/chainmaker.yml.backup
        sed -i '158s/false/true/g' ./release/$file/config/node$i/chainmaker.yml
        sed -i '517s/leveldb/sql/g' ./release/$file/config/node$i/chainmaker.yml
        sed -i '518s/leveldb_config:/sqldb_config:/g' ./release/$file/config/node$i/chainmaker.yml
        sed -i '519s/store_path:.*/sqldb_type: mysql/g' ./release/$file/config/node$i/chainmaker.yml
        sed -i '520i\      dsn: root:root@tcp(127.0.0.1:'$port')\/' ./release/$file/config/node$i/chainmaker.yml
    fi
done

# 启动
for file in `ls ./release`
do
    if [ $file ]; then
        echo "START ==> ./release/"$file
        cd ./release/$file/bin && ./start.sh -f full && cd - > /dev/null
    fi
done

echo "Waiting ==> Service start..."
sleep 5

netstat -lptn | grep 1230